import { useEffect, useState, useRef } from "react";
function useScanCode(timerCount = 5) {
    const [count, setCount] = useState(timerCount);
    const timerRef = useRef(null);
    const scanCode = () => {
        // 防止用户多次点击
        if (!timerRef.current) {
            timerRef.current = setInterval(() => {
                setCount((count) => count - 1);
            }, 1000);
        }
    };
    // 获取最新的count
    useEffect(() => {
        if (count === 0) {
            clearInterval(timerRef.current);
            // 重置计数器的值
            setCount(timerCount);
            timerRef.current = null;
        }
    }, [count]);
    return [count, timerCount, scanCode];
}
function App() {
    const [count, timerCount, scanCode] = useScanCode();
    return (
        // count === timerCount => 初始状态
        <div>
            <button
                disabled={count !== timerCount}
                onClick={count === timerCount ? scanCode : null}>
                {count === timerCount ? "发送验证码" : `${count}s`}
            </button>
        </div>
    );
}
export default App;
